#include "sg_ffmpeg_dec.h"
#include "AudioDecode.h"

#include <iostream>
#include <new> // std::nothrow

sg_ffmpeg_ins* sg_ffmpeg_create(int out_sample_rate)
{
    auto p = new(std::nothrow) AudioDecode(out_sample_rate);
    //if(p->init()<0)
    //{
        //delete p;
        //return NULL;
    //}
    return reinterpret_cast<sg_ffmpeg_ins*>(p);
}

void sg_ffmpeg_release(sg_ffmpeg_ins* dec)
{
    if (0 != dec)
    {
        auto pp = reinterpret_cast<AudioDecode*>(dec);
        delete pp;
    }
}

void sg_ffmpeg_start(sg_ffmpeg_ins* dec)
{
    if (0 != dec)
    {
        auto pp = reinterpret_cast<AudioDecode*>(dec);
        pp->start();
    }
}

void sg_ffmpeg_stop(sg_ffmpeg_ins* dec)
{
    if (0 != dec)
    {
        auto pp = reinterpret_cast<AudioDecode*>(dec);
        pp->stop();
    }
}

int sg_ffmpeg_send_data(sg_ffmpeg_ins* dec, char* indata, int inlen)
{
    if (0 != dec)
    {
        auto d = reinterpret_cast<AudioDecode*>(dec);
        return d->send_data((const uint8_t*)indata, inlen);
    }
    else{
        return -10;
    }
}

int sg_ffmpeg_send_all(sg_ffmpeg_ins* dec, char* indata, int inlen)
{
    if (0 != dec)
    {
        auto d = reinterpret_cast<AudioDecode*>(dec);
        int sz = 0;
        while(sz<inlen)
        {
            int out_len = d->send_data((const uint8_t*)indata+sz, inlen-sz);
            if (out_len < 0) {
                fprintf(stderr, "Error while send_data\n");
                return out_len;
            }
            sz += out_len;
        }
        return inlen;
    }
    else{
        return -10;
    }
}

int sg_ffmpeg_decode(sg_ffmpeg_ins* dec, char* outdata, int* outlen)
{
    if (0 != dec)
    {
        auto d = reinterpret_cast<AudioDecode*>(dec);
        uint8_t* out_buffer;
        int out_len = d->decode(&out_buffer);
        if (out_len < 0) {
            //fprintf(stderr, "Error while parsing\n");
            return out_len;
        }

        if (*outlen < out_len) {
            memcpy(outdata, out_buffer, *outlen);
            return -3;
        }else{
            *outlen = out_len;
            memcpy(outdata, out_buffer, *outlen);
            return *outlen;
        }
    }
    else{
        return -10;
    }
}

